import { useEffect, useState } from 'react';

// 避免在!value出现value=0时导致错误
export const isFalsy = (value: unknown): boolean =>
    value === 0 ? false : !value; //!!将值转化为布尔值

/**
 * 清除对象中的空值
 * @param {*} object
 * @returns Object
 */
export const cleanObject = (object: object) => {
    const result = { ...object };
    Object.keys(object).forEach((key) => {
        //@ts-ignore
        const value = result[key];
        if (isFalsy(value)) {
            //@ts-ignore
            delete result[key];
        }
    });
    return result;
};

export const useMount = (callback: () => void) => {
    useEffect(() => {
        callback();
    }, []);
};

//使用泛型来规范类型
export const useDebounce = <S>(value: S, delay?: number): S => {
    const [debounceValue, setDebounceValue] = useState(value);
    useEffect(() => {
        const timeout = setTimeout(() => setDebounceValue(value), delay);
        return () => {
            clearTimeout(timeout);
        };
    }, [value, delay]);

    return debounceValue;
};
